package it.cast.wechat.cotroller;

import com.alibaba.fastjson.JSONObject;
import it.cast.wechat.utils.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author wangjie41
 * @version 2020/4/24 18:02
 */
@Controller
public class UserController {
    /**
     * 通过微信小程序的穿过来的code，获取openId，并返回到微信小程序
     * */
    @RequestMapping(value = "/wx/user/login")
    @ResponseBody
    public Map<String, String> login(String code) {
        //wx4092d49091f7f444
        String appId = "wx87a8b1a6c3fb5c42";
        String appSecret = "4399546244103c57664f08df34e63204";
        // 请求参数
        String params = "appid="+appId+"&secret="+appSecret+"&js_code="+code
                +"&grant_type=authorization_code";


        String url = "https://api.weixin.qq.com/sns/jscode2session";
        String result = HttpRequest.sendGet(url, params);
        System.out.println("返回的结果："+result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String openId = jsonObject.getString("openid");

        System.out.println("微信小程序传过来的code"+code);
        Set<String> keySet = jsonObject.keySet();
        for (String eachKey:keySet) {
            System.out.print(eachKey+"  ");
        }

        Map<String, String> resultMap = new HashMap<>();
        //o_BG25HWfEEnfy4llAMZdS9CYTH0
        resultMap.put("openId", openId);
        return resultMap;
    }
}
